import * as echarts from "echarts";
import { type Ref, onBeforeUnmount, onMounted, ref, markRaw } from "vue";
export function useChart(chartRef: Ref<HTMLElement | null>, initOptions: any) {
  const chartInstance = ref<echarts.ECharts | null>(null);
  const chartOptions = ref<any>(initOptions);

  const initChart = () => {
    if (chartRef.value) {
      chartInstance.value = markRaw(echarts.init(chartRef.value));
      chartInstance.value.setOption(chartOptions.value);
    }
  };
  const reSizeChart = () => {
    chartInstance.value?.resize();
  };
  onMounted(() => {
    initChart();
    window.addEventListener("resize", reSizeChart);
  });
  onBeforeUnmount(() => {
    window.removeEventListener("resize", reSizeChart);
    if (chartInstance.value) {
      chartInstance.value.dispose(); //释放图标所占用的资源
    }
  });
}
